package com.zdxc.service;

import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.zdxc.entities.Taskplan;
import com.zdxc.vo.TaskplanVO;
import common.dao.BaseMyBatisDAO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;



import common.bean.Paging;
import common.util.DateUtils;
import common.util.UserInfoUtils;


/**
 * 工作计划管理模块Service接口实现
 *
 * @author liuxj
 * @version 1.0.0 2017-08-08
 */
@Lazy
@Service
public class TaskPlanService   {
    @Autowired
    BaseMyBatisDAO baseMyBatisDAO;
    /** SQL的命名空间 */
    private static final String SQL_NS = "com.zdxc.dao.Taskplan.";
   // private static final String SQL_task = "dailymgt.task.";
    private Logger logger = Logger.getLogger(this.getClass());

    /**
     * 根据分页条件查询工作计划数据并分页
     *
     * @param taskplan
     *            查询参数
     * @param paging
     *            分页参数
     * @return 分页数据
     */
    public Paging findByCondition(Taskplan taskplan, Paging paging) {

        paging.setStringParams(taskplan);

        paging = baseMyBatisDAO.findForPageHelper(SQL_NS + "findByCondition", paging);

        return paging;
    }

    /**
     * 外部接口取数据
     *
     * @param map
     * @return
     */
    public List<TaskplanVO> findTaskplanRemoteByCondition(Map<String, Object> map) {
        List<TaskplanVO> list = baseMyBatisDAO.findForList(SQL_NS + "findTaskplanRemoteByCondition", map);
        return list;
    }

    /**
     * 新增工作计划
     *
     * @param taskplan
     *            工作计划
     */
    public void addTaskplan(Taskplan taskplan) {
        taskplan.setsPlanId(common.util.StringUtils.getUUID());
        baseMyBatisDAO.insert(SQL_NS+"insert",taskplan);
        //insert()


    }

    /**
     * 修改工作计划
     *
     * @param Taskplan
     *            工作计划
     */
    public void modifyTaskplan(Taskplan Taskplan) {
        baseMyBatisDAO.update(SQL_NS+"update",Taskplan);
        //	baseJpaDAO.merge(Taskplan);

    }

	/*public  void SetProgess(Taskplan Taskplan) {

		Map<String, Object> taskMap = new HashMap<String, Object>();
		taskMap.put("taskId", Taskplan.getTaskId());
		List<TaskplanVO> TaskplanList = findTaskplanRemoteByCondition(taskMap);
		Double finishedCount = 0.00;
		for (TaskplanVO TaskplanVO : TaskplanList) {
			if (StringUtils.equals(TaskplanVO.getStatusCd(), "1")) {
				finishedCount = finishedCount + 1;
			}
		}
		double progess = (finishedCount / TaskplanList.size()) * 100;
		String progessStr = String.valueOf(Math.round(progess)) + "%";

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("sid", Taskplan.getTaskId());
		param.put("progress", progessStr);
		if (!StringUtils.isBlank(Taskplan.getTaskId())) {
			baseMyBatisDAO.update(SQL_task + "updateTaskBySId", param);
		}
	}*/

    /***
     * 修改工作计划
     *
     * @param taskplan
     */
    public String saveByTaskplan(Taskplan taskplan) {

        if (StringUtils.isNotBlank(taskplan.getsPlanId())) {
            Taskplan saveEntity = findTaskplanById(taskplan.getsPlanId());
            if (saveEntity != null) {

                BeanUtils.copyProperties(taskplan, saveEntity);
                modifyTaskplan(saveEntity);
            }
            return saveEntity.getsPlanId();
        } else {      //保存
            taskplan.setRecordStatus(1);
            taskplan.setsPlanId(common.util.StringUtils.getUUID());
            baseMyBatisDAO.insert(SQL_NS+"insert",taskplan);
            return taskplan.getsPlanId();
        }
    }

    /**
     * 批量删除工作计划
     *
     * @param idList
     *            ID列表
     */
    public void deleteTaskplanByIds(List<String> idList) {
        baseMyBatisDAO.delete(SQL_NS + "deleteTaskplanByIds", idList);
    }

    /**
     * 批量删除工作计划
     *
     * @param idList
     *            TaskID列表
     */
    public void deleteTaskplanByTaskIds(List<String> idList) {
        baseMyBatisDAO.delete(SQL_NS + "deleteTaskplanByTaskIds", idList);
    }

    /**
     * 根据ID查询工作计划
     *
     * @param sPlanId
     * @return Taskplan
     */
    public Taskplan findTaskplanById(String sPlanId) {
        return baseMyBatisDAO.findUnique(SQL_NS+"selectByKey", sPlanId);
    }

    /**
     * 导入Excel
     *
     * @param multipartFile
     *            -- 导入的文件名
     * @param taskSid
     *            -- 对应数据库中主表的主健(tasksid)
     * @param tableName
     *            -- 对应数据库中的表名()
     *//*
	public void importExcel(MultipartFile multipartFile, String taskSid, String tableName) {
		// 1.创建工作簿
		*//** 我们要操作的工作簿(ps:Excel中的表,要导入的模板) *//*
		Workbook workbook = null;
		InputStream is = null;
		// System.out.println(multipartFile);
		try {
			if (multipartFile != null && !multipartFile.isEmpty()) {

				// 得到输入流
				is = multipartFile.getInputStream();

				// 得到工作簿
				workbook = new XSSFWorkbook(is);

				// 得到一张表(ps:可能一个工作簿有多张表在这不考虑)
				Sheet sheet = workbook.getSheetAt(0);

				// 得到头行(ps:标题行)
				Row headRow = sheet.getRow(0);

				// 总共几行
				int rowsNum = sheet.getLastRowNum();

				// 得到列数
				int colsNum = headRow.getLastCellNum();

				// System.out.println(tableName);
				if (StringUtils.equals(tableName, "S_TASK_PLAN")) {
					insertTaskplan(sheet, rowsNum, colsNum, taskSid);
				}
			}
		} catch (Exception e) {
			// throw new RuntimeException(e);
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new RuntimeException("关闭文件读取流报错！");
			}
		}

	}*/

    /**
     * 将Excel中的数据插入到数据库中
     *
     * @param sheet
     *            -- Excel中的表
     * @param rowsNum
     *            -- 总行数
     * @param colsNum
     *            -- 总列数
     * @param whbyxmSid
     *            -- 数据库表中的sid(ps:主健)
     * @param tableName
     *            -- 数据库中的表名
     *//*
	private void insertTaskplan(Sheet sheet, int rowsNum, int colsNum, String taskSid) {
		String fullName = UserInfoUtils.getFullName();

		// 采用循环读写
		Row row = null;
		Cell cols = null;

		List<Taskplan> planList = new ArrayList<Taskplan>();

		for (int i = 1; i <= rowsNum; i++) {// 行

			Taskplan Taskplan = new Taskplan();
			row = sheet.getRow(i);
			for (int j = 0; j < colsNum; j++) {// 列
				cols = row.getCell(j);
				String val = getValue(cols);
				switch (j) {
				case 1:
					Taskplan.setWorkType(val);
					break;
				case 2:
					Taskplan.setWorkContent(val);
					break;
				case 3:
					Taskplan.setRequirement(val);
					break;
				case 4:
					try {
						Date plandate = DateUtils.strToDate(val, "yyyy-MM-dd");
						Taskplan.setPlanTime(plandate);
					} catch (Exception e) {
						throw new RuntimeException("导入失败，第" + rowsNum + "行，第5列日期格式不正确，请参数格式：2017-08-01");
					}
					break;
				case 5:
					Taskplan.setTimePeriod(val);
					break;
				case 6:
					Taskplan.setAddress(val);
					break;
				case 7:
					Taskplan.setOrganizingMan(val);
					break;
				case 8:
					Taskplan.setDutyUnit(val);
					break;
				default:
					// System.out.println(val);
					break;
				}

			}
			// 插入
			Taskplan.setTaskId(taskSid);
			Taskplan.setRecordStatus(1);
			Taskplan.setCreatedBy(fullName);
			Taskplan.setLastUpdatedBy(fullName);
			planList.add(Taskplan);
		}
		baseMyBatisDAO.insert(SQL_NS + "insertSTaskplans", planList);

	}
*/
    /**
     * 获取到单元格的值
     *
     * @param cell
     * @return
     *//*
	@SuppressWarnings("deprecation")
	private String getValue(Cell cell) {
		if (cell == null) {
			return StringUtils.EMPTY;
		}
		if (Cell.CELL_TYPE_BOOLEAN == cell.getCellType()) {
			return String.valueOf(cell.getBooleanCellValue());
		} else if (Cell.CELL_TYPE_NUMERIC == cell.getCellType()) {
			DecimalFormat df = new DecimalFormat("#.######");
			return df.format(cell.getNumericCellValue());
		} else {
			return cell.getStringCellValue();
		}
	}*/

    /**
     * ipad数据处理
     *
     * @param TaskplanList
     */
    public void SetTaskplan(List<TaskplanVO> TaskplanList) {
        if (CollectionUtils.isNotEmpty(TaskplanList)) {
            for (TaskplanVO Taskplanvo : TaskplanList) {
                String sidjh = Taskplanvo.getsPlanId();
                if (StringUtils.isNotEmpty(sidjh)) {
                    Taskplan taskplan = baseMyBatisDAO.findUnique(SQL_NS+"selectById", sidjh);
                    if (taskplan == null) {  //新增

                        taskplan = new Taskplan();
                        BeanUtils.copyProperties(Taskplanvo, taskplan);

                        taskplan.setRecordStatus(1);
                        baseMyBatisDAO.insert(SQL_NS+"insert" ,taskplan);

                    } else {                       //修改
                        BeanUtils.copyProperties(Taskplanvo, taskplan);
                        taskplan.setRecordStatus(1);
                        baseMyBatisDAO.update(SQL_NS+"update" ,taskplan);
                    }
                } else {
                    throw new RuntimeException();
                }
            }
        }

    }

}
